package com.buaa.divinationmaster.algorithm;

import android.content.Context;

import com.buaa.divinationmaster.model.TarotCard;
import com.buaa.divinationmaster.interpretation.InterpretationEngine;
import com.buaa.divinationmaster.interpretation.ContextAnalyzer;
import java.util.*;

/**
 * 塔罗牌占卜算法引擎
 * 实现完整的塔罗牌占卜逻辑，包括洗牌、抽牌、解读
 */
public class TarotAlgorithm {
    
    /**
     * 抽到的牌（带位置和方向）
     */
    public static class DrawnCard {
        private TarotCard card;            // 塔罗牌
        private int position;              // 牌阵中的位置
        private boolean isReversed;        // 是否逆位
        private String positionMeaning;    // 该位置的含义
        
        public DrawnCard(TarotCard card, int position, boolean isReversed, String positionMeaning) {
            this.card = card;
            this.position = position;
            this.isReversed = isReversed;
            this.positionMeaning = positionMeaning;
        }
        
        // Getters
        public TarotCard getCard() { return card; }
        public int getPosition() { return position; }
        public boolean isReversed() { return isReversed; }
        public String getPositionMeaning() { return positionMeaning; }
    }
    
    /**
     * 塔罗牌阵结果
     */
    public static class TarotReading {
        private String question;           // 问题
        private SpreadType spreadType;     // 牌阵类型
        private List<DrawnCard> cards;     // 抽到的牌
        private String interpretation;     // 综合解读
        private String lifestyleInterpretation; // 生活化解读
        private long timestamp;            // 占卜时间
        
        public TarotReading(String question, SpreadType spreadType, List<DrawnCard> cards) {
            this.question = question;
            this.spreadType = spreadType;
            this.cards = cards;
            this.timestamp = System.currentTimeMillis();
            this.interpretation = generateInterpretation(cards, spreadType);
            this.lifestyleInterpretation = null; // 需要通过Context生成
        }
        
        /**
         * 使用生活化解读引擎生成解读
         */
        public TarotReading(String question, SpreadType spreadType, List<DrawnCard> cards, Context context) {
            this.question = question;
            this.spreadType = spreadType;
            this.cards = cards;
            this.timestamp = System.currentTimeMillis();
            this.interpretation = generateInterpretation(cards, spreadType);
            
            // 生成生活化解读
            if (context != null) {
                this.lifestyleInterpretation = generateLifestyleInterpretation(question, this.interpretation, context);
            }
        }
        
        // Getters
        public String getQuestion() { return question; }
        public SpreadType getSpreadType() { return spreadType; }
        public List<DrawnCard> getCards() { return cards; }
        public String getInterpretation() { return interpretation; }
        public String getLifestyleInterpretation() { return lifestyleInterpretation; }
        public long getTimestamp() { return timestamp; }
        
        /**
         * 生成生活化解读
         */
        private String generateLifestyleInterpretation(String question, String originalInterpretation, Context context) {
            try {
                InterpretationEngine engine = new InterpretationEngine(context);
                InterpretationEngine.InterpretationResult result = engine.generateLifestyleInterpretation(
                    originalInterpretation, 
                    question != null ? question : "", 
                    InterpretationEngine.InterpretationStyle.FRIENDLY
                );
                return result.getFormattedInterpretation();
            } catch (Exception e) {
                // 如果生活化解读失败，返回原始解读
                return originalInterpretation;
            }
        }
        
        /**
         * 生成综合解读
         */
        private String generateInterpretation(List<DrawnCard> cards, SpreadType spreadType) {
            StringBuilder sb = new StringBuilder();
            
            sb.append("【").append(spreadType.getName()).append("解读】\n\n");
            
            // 根据牌阵类型生成不同的解读
            switch (spreadType) {
                case ONE_CARD:
                    sb.append(generateOneCardInterpretation(cards.get(0)));
                    break;
                case THREE_CARD:
                    sb.append(generateThreeCardInterpretation(cards));
                    break;
                case FIVE_CARD:
                    sb.append(generateFiveCardInterpretation(cards));
                    break;
                case CELTIC_CROSS:
                    sb.append(generateCelticCrossInterpretation(cards));
                    break;
            }
            
            sb.append("\n\n【总结建议】\n");
            sb.append(generateAdvice(cards));
            
            return sb.toString();
        }
        
        private String generateOneCardInterpretation(DrawnCard drawnCard) {
            StringBuilder sb = new StringBuilder();
            TarotCard card = drawnCard.getCard();
            boolean reversed = drawnCard.isReversed();
            
            sb.append("您抽到的是：").append(card.getDisplayName());
            sb.append(reversed ? "（逆位）" : "（正位）").append("\n\n");
            
            sb.append("【关键词】\n");
            sb.append(card.getKeywords(reversed)).append("\n\n");
            
            sb.append("【含义解读】\n");
            sb.append(card.getMeaning(reversed)).append("\n");
            
            return sb.toString();
        }
        
        private String generateThreeCardInterpretation(List<DrawnCard> cards) {
            StringBuilder sb = new StringBuilder();
            String[] positions = {"过去", "现在", "未来"};
            
            for (int i = 0; i < cards.size(); i++) {
                DrawnCard drawnCard = cards.get(i);
                TarotCard card = drawnCard.getCard();
                boolean reversed = drawnCard.isReversed();
                
                sb.append("【").append(positions[i]).append("】");
                sb.append(card.getDisplayName());
                sb.append(reversed ? "（逆位）" : "（正位）").append("\n");
                sb.append(card.getMeaning(reversed)).append("\n\n");
            }
            
            return sb.toString();
        }
        
        private String generateFiveCardInterpretation(List<DrawnCard> cards) {
            StringBuilder sb = new StringBuilder();
            String[] positions = {"过去影响", "当前状况", "未来发展", "潜意识/障碍", "建议/结果"};
            
            for (int i = 0; i < cards.size(); i++) {
                DrawnCard drawnCard = cards.get(i);
                TarotCard card = drawnCard.getCard();
                boolean reversed = drawnCard.isReversed();
                
                sb.append("【").append(positions[i]).append("】");
                sb.append(card.getDisplayName());
                sb.append(reversed ? "（逆位）" : "（正位）").append("\n");
                sb.append(card.getMeaning(reversed)).append("\n\n");
            }
            
            return sb.toString();
        }
        
        private String generateCelticCrossInterpretation(List<DrawnCard> cards) {
            StringBuilder sb = new StringBuilder();
            String[] positions = {
                "当前状况", "阻碍/挑战", "最佳状况/目标", "过去基础", "近期过去",
                "近期未来", "你的态度", "外部环境", "希望/恐惧", "最终结果"
            };
            
            for (int i = 0; i < cards.size(); i++) {
                DrawnCard drawnCard = cards.get(i);
                TarotCard card = drawnCard.getCard();
                boolean reversed = drawnCard.isReversed();
                
                sb.append("【").append(positions[i]).append("】");
                sb.append(card.getDisplayName());
                sb.append(reversed ? "（逆位）" : "（正位）").append("\n");
                sb.append(card.getMeaning(reversed)).append("\n\n");
            }
            
            return sb.toString();
        }
        
        private String generateAdvice(List<DrawnCard> cards) {
            // 基于抽到的牌生成建议
            boolean hasPositiveCards = cards.stream().anyMatch(c -> !c.isReversed());
            boolean hasNegativeCards = cards.stream().anyMatch(DrawnCard::isReversed);
            
            StringBuilder advice = new StringBuilder();
            
            if (hasPositiveCards && !hasNegativeCards) {
                advice.append("整体运势良好，保持积极的心态继续前进。");
            } else if (hasNegativeCards && !hasPositiveCards) {
                advice.append("目前可能面临一些挑战，建议谨慎行事，多听取他人意见。");
            } else {
                advice.append("运势有起有伏，保持平衡心态，在困难中寻找机会。");
            }
            
            advice.append("记住，塔罗牌只是提供指引，最终的决定权还是在您手中。");
            
            return advice.toString();
        }
    }
    
    /**
     * 牌阵类型枚举
     */
    public enum SpreadType {
        ONE_CARD("单张牌", 1, new String[]{"指引"}),
        THREE_CARD("三张牌", 3, new String[]{"过去", "现在", "未来"}),
        FIVE_CARD("五张牌", 5, new String[]{"过去影响", "当前状况", "未来发展", "潜意识/障碍", "建议/结果"}),
        CELTIC_CROSS("凯尔特十字", 10, new String[]{
            "当前状况", "阻碍/挑战", "最佳状况/目标", "过去基础", "近期过去",
            "近期未来", "你的态度", "外部环境", "希望/恐惧", "最终结果"
        });
        
        private String name;
        private int count;
        private String[] positionNames;
        
        SpreadType(String name, int count, String[] positionNames) {
            this.name = name;
            this.count = count;
            this.positionNames = positionNames;
        }
        
        public String getName() { return name; }
        public int getCount() { return count; }
        public String[] getPositionNames() { return positionNames; }
    }
    
    /**
     * 执行塔罗牌占卜
     */
    public static TarotReading performReading(String question, SpreadType spreadType, List<TarotCard> deck) {
        // 洗牌
        List<TarotCard> shuffledDeck = new ArrayList<>(deck);
        Collections.shuffle(shuffledDeck, new Random(System.currentTimeMillis()));
        
        // 抽牌
        List<DrawnCard> drawnCards = new ArrayList<>();
        String[] positionNames = spreadType.getPositionNames();
        
        for (int i = 0; i < spreadType.getCount(); i++) {
            TarotCard card = shuffledDeck.get(i);
            boolean isReversed = new Random().nextBoolean(); // 50%概率逆位
            String positionMeaning = positionNames[i];
            
            drawnCards.add(new DrawnCard(card, i, isReversed, positionMeaning));
        }
        
        // 生成解读结果
        return new TarotReading(question, spreadType, drawnCards);
    }
    
    /**
     * 创建标准78张塔罗牌库
     */
    public static List<TarotCard> createStandardDeck() {
        List<TarotCard> deck = new ArrayList<>();
        
        // 添加22张大阿卡纳
        String[] majorArcanaZh = {
            "愚者", "魔术师", "女祭司", "女皇", "皇帝", "教皇", "恋人", "战车", 
            "力量", "隐者", "命运之轮", "正义", "倒吊人", "死神", "节制", 
            "恶魔", "塔", "星星", "月亮", "太阳", "审判", "世界"
        };
        
        String[] majorArcanaEn = {
            "The Fool", "The Magician", "The High Priestess", "The Empress", "The Emperor", 
            "The Hierophant", "The Lovers", "The Chariot", "Strength", "The Hermit", 
            "Wheel of Fortune", "Justice", "The Hanged Man", "Death", "Temperance", 
            "The Devil", "The Tower", "The Star", "The Moon", "The Sun", "Judgement", "The World"
        };
        
        for (int i = 0; i < 22; i++) {
            TarotCard card = new TarotCard(i, majorArcanaZh[i], majorArcanaEn[i], TarotCard.CardType.MAJOR_ARCANA);
            card.setSuit(TarotCard.Suit.NONE);
            card.setUprightKeywords("正面能量,成长,机会");
            card.setUprightMeaning("这张牌代表积极的能量和成长的机会。");
            card.setReversedKeywords("阻碍,延迟,内在冲突");
            card.setReversedMeaning("可能面临一些阻碍或需要内省的时期。");
            deck.add(card);
        }
        
        // 添加56张小阿卡纳
        TarotCard.Suit[] suits = {TarotCard.Suit.WANDS, TarotCard.Suit.CUPS, TarotCard.Suit.SWORDS, TarotCard.Suit.PENTACLES};
        String[] suitNamesZh = {"权杖", "圣杯", "宝剑", "星币"};
        String[] suitNamesEn = {"Wands", "Cups", "Swords", "Pentacles"};
        String[] courtCardsZh = {"侍从", "骑士", "王后", "国王"};
        String[] courtCardsEn = {"Page", "Knight", "Queen", "King"};
        
        int cardId = 22;
        for (int suitIndex = 0; suitIndex < 4; suitIndex++) {
            TarotCard.Suit suit = suits[suitIndex];
            String suitZh = suitNamesZh[suitIndex];
            String suitEn = suitNamesEn[suitIndex];
            
            // 数字牌 A-10
            for (int num = 1; num <= 10; num++) {
                TarotCard card = new TarotCard(cardId++, 
                    suitZh + (num == 1 ? "A" : String.valueOf(num)), 
                    (num == 1 ? "Ace" : String.valueOf(num)) + " of " + suitEn, 
                    TarotCard.CardType.MINOR_ARCANA);
                card.setSuit(suit);
                card.setNumber(num);
                card.setUprightKeywords("发展,进步,能量");
                card.setUprightMeaning("这张牌代表在" + suitZh + "领域的积极发展。");
                card.setReversedKeywords("停滞,阻碍,逆转");
                card.setReversedMeaning("在" + suitZh + "方面可能遇到一些挑战。");
                deck.add(card);
            }
            
            // 宫廷牌
            for (int courtIndex = 0; courtIndex < 4; courtIndex++) {
                TarotCard card = new TarotCard(cardId++, 
                    suitZh + courtCardsZh[courtIndex], 
                    courtCardsEn[courtIndex] + " of " + suitEn, 
                    TarotCard.CardType.MINOR_ARCANA);
                card.setSuit(suit);
                card.setNumber(11 + courtIndex);
                card.setUprightKeywords("权威,掌控,成熟");
                card.setUprightMeaning("代表在" + suitZh + "领域的成熟和掌控能力。");
                card.setReversedKeywords("失控,不成熟,滥用权力");
                card.setReversedMeaning("可能在" + suitZh + "方面缺乏控制或过于冲动。");
                deck.add(card);
            }
        }
        
        return deck;
    }
}
